<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
    <style>
      * {
        margin: 0;
        padding: 0;
        box-sizing: border-box;
      }

      body {
        width: 100vw;
        height: 100vh;
        display: flex;
        justify-content: center;
      }

      #game-container {
        width: 33.33vw;
        height: 100vh;
        background-color: black;
        position: relative;
        overflow: hidden;
      }

      #player {
        width: 50px;
        height: 50px;
        position: absolute;
        bottom: 50px;
        left: 50%;
        transform: translateX(-50%);
        transition: left 0.1s linear;
      }

      .bullet {
        width: 4px;
        height: 10px;
        background-color: white;
        position: absolute;
        border-radius: 2px;
        transform: translateX(-50%);
      }

      .enemy-ship {
        width: 40px;
        height: 40px;
        position: absolute;
        transform: rotate(180deg) translateX(50%);
      }

      .enemy-ship.hit {
        animation: flash 0.2s;
      }

      @keyframes flash {
        0%,
        100% {
          opacity: 1;
        }
        50% {
          opacity: 0.3;
        }
      }

      #start-button {
        position: absolute;
        top: 50%;
        left: 50%;
        transform: translate(-50%, -50%);
        padding: 15px 30px;
        font-size: 24px;
        background-color: #4caf50;
        color: white;
        border: none;
        border-radius: 5px;
        cursor: pointer;
        transition: background-color 0.3s;
      }

      #start-button:hover {
        background-color: #45a049;
      }

      .game-paused {
        display: none;
      }

      .bullet.rage {
        background-color: #ff4444; /* 暴走模式下子弹颜色变红 */
      }

      #rage-indicator {
        position: absolute;
        top: 20px;
        left: 50%;
        transform: translateX(-50%);
        color: #ff4444;
        font-size: 24px;
        font-weight: bold;
        display: none;
      }

      #score-container {
        position: absolute;
        top: 20px;
        right: 20px;
        color: white;
        font-size: 24px;
        font-family: Arial, sans-serif;
        display: none;
      }

      .score-popup {
        position: absolute;
        color: #4caf50;
        font-weight: bold;
        font-size: 28px;
        pointer-events: none;
        text-shadow: 0 0 10px rgba(76, 175, 80, 0.5);
        animation: scorePopup 1s cubic-bezier(0.23, 1, 0.32, 1) forwards;
        z-index: 100;
      }

      @keyframes scorePopup {
        0% {
          transform: scale(0.1) translateY(0);
          opacity: 0;
        }
        20% {
          transform: scale(1.5) translateY(0);
          opacity: 1;
        }
        50% {
          transform: scale(1.2) translateY(-20px);
          opacity: 1;
        }
        100% {
          transform: scale(1) translateY(-40px);
          opacity: 0;
        }
      }

      .score-highlight {
        animation: scoreHighlight 0.5s cubic-bezier(0.175, 0.885, 0.32, 1.275);
        text-shadow: 0 0 15px #4caf50;
      }

      @keyframes scoreHighlight {
        0% {
          transform: scale(1);
          color: white;
        }
        30% {
          transform: scale(1.5);
          color: #4caf50;
        }
        70% {
          transform: scale(1.2);
          color: #4caf50;
        }
        100% {
          transform: scale(1);
          color: white;
        }
      }

      #game-over-container {
        position: absolute;
        top: 50%;
        left: 50%;
        transform: translate(-50%, -50%);
        text-align: center;
        color: white;
        display: none;
      }

      #game-over-title {
        font-size: 48px;
        color: #ff4444;
        margin-bottom: 20px;
        text-shadow: 0 0 10px rgba(255, 68, 68, 0.5);
      }

      .game-over-text {
        font-size: 24px;
        margin: 10px 0;
      }

      #restart-button {
        padding: 15px 30px;
        font-size: 24px;
        background-color: #4caf50;
        color: white;
        border: none;
        border-radius: 5px;
        cursor: pointer;
        transition: background-color 0.3s;
        margin-top: 20px;
      }

      #restart-button:hover {
        background-color: #45a049;
      }

      .side-panel {
        width: 33.33vw;
        height: 100vh;
        background-color: #1a1a1a;
        padding: 20px;
        color: white;
        font-family: Arial, sans-serif;
      }

      .panel-title {
        font-size: 24px;
        color: #4caf50;
        margin-bottom: 20px;
        text-align: center;
        text-shadow: 0 0 10px rgba(76, 175, 80, 0.3);
      }

      .stat-box {
        background-color: #2a2a2a;
        border-radius: 8px;
        padding: 15px;
        margin-bottom: 15px;
      }

      .stat-label {
        font-size: 14px;
        color: #888;
        margin-bottom: 5px;
      }

      .stat-value {
        font-size: 24px;
        color: #fff;
        text-shadow: 0 0 5px rgba(255, 255, 255, 0.3);
      }

      .achievement {
        display: flex;
        align-items: center;
        padding: 10px;
        background-color: #2a2a2a;
        border-radius: 8px;
        margin-bottom: 10px;
      }

      .achievement-icon {
        width: 30px;
        height: 30px;
        background-color: #4caf50;
        border-radius: 50%;
        margin-right: 10px;
        display: flex;
        align-items: center;
        justify-content: center;
      }

      .achievement-locked {
        opacity: 0.5;
      }

      .achievement-info {
        flex-grow: 1;
      }

      .achievement-name {
        font-size: 16px;
        margin-bottom: 3px;
      }

      .achievement-desc {
        font-size: 12px;
        color: #888;
      }

      #history-list {
        max-height: 200px;
        overflow-y: auto;
      }

      .history-item {
        padding: 8px;
        border-bottom: 1px solid #333;
        font-size: 14px;
      }

      .history-item:last-child {
        border-bottom: none;
      }

      .history-time {
        color: #888;
        font-size: 12px;
      }
    </style>
  </head>
  <body>
    <div class="side-panel">
      <div class="panel-title">游戏数据</div>
      <div class="stat-box">
        <div class="stat-label">最高分数</div>
        <div class="stat-value" id="high-score">0</div>
      </div>
      <div class="stat-box">
        <div class="stat-label">累计击败敌人</div>
        <div class="stat-value" id="total-kills">0</div>
      </div>
      <div class="stat-box">
        <div class="stat-label">最长游戏时间</div>
        <div class="stat-value" id="longest-time">0:00</div>
      </div>
      <div class="panel-title">成就</div>
      <div class="achievement">
        <div class="achievement-icon">★</div>
        <div class="achievement-info">
          <div class="achievement-name">初次暴走</div>
          <div class="achievement-desc">第一次触发暴走模式</div>
        </div>
      </div>
      <div class="achievement achievement-locked">
        <div class="achievement-icon">★</div>
        <div class="achievement-info">
          <div class="achievement-name">百发百中</div>
          <div class="achievement-desc">连续击中10次敌人</div>
        </div>
      </div>
    </div>

    <div id="game-container">
      <div id="rage-indicator">暴走模式!</div>
      <div id="score-container">得分: <span id="score">0</span></div>
      <img id="player" src="static/player.svg" alt="player" class="game-paused" />
      <button id="start-button">开始游戏</button>
      <div id="game-over-container">
        <div id="game-over-title">游戏结束</div>
        <div class="game-over-text">最终得分: <span id="final-score">0</span></div>
        <div class="game-over-text">游戏时长: <span id="game-duration">0:00</span></div>
        <button id="restart-button">重新开始</button>
      </div>
    </div>

    <div class="side-panel">
      <div class="panel-title">游戏历史</div>
      <div id="history-list">
        <!-- 历史记录会动态添加在这里 -->
      </div>
      <div class="panel-title">实时数据</div>
      <div class="stat-box">
        <div class="stat-label">命中率</div>
        <div class="stat-value" id="accuracy">0%</div>
      </div>
      <div class="stat-box">
        <div class="stat-label">击杀速率</div>
        <div class="stat-value" id="kill-rate">0/分钟</div>
      </div>
    </div>

    <script>
      const gameContainer = document.getElementById('game-container')
      const player = document.getElementById('player')
      const startButton = document.getElementById('start-button')
      const scoreElement = document.getElementById('score')
      const scoreContainer = document.getElementById('score-container')
      const gameOverContainer = document.getElementById('game-over-container')
      const finalScoreElement = document.getElementById('final-score')
      const gameDurationElement = document.getElementById('game-duration')
      const restartButton = document.getElementById('restart-button')
      const highScoreElement = document.getElementById('high-score')
      const totalKillsElement = document.getElementById('total-kills')
      const longestTimeElement = document.getElementById('longest-time')
      const accuracyElement = document.getElementById('accuracy')
      const killRateElement = document.getElementById('kill-rate')
      const historyList = document.getElementById('history-list')

      // 游戏配置参数
      const gameConfig = {
        player: {
          moveSpeed: 5,
          initialPosition: 50,
          rageSpeedMultiplier: 2 // 暴走时移动速度倍数
        },
        bullet: {
          fireInterval: 200,
          speed: 1000,
          checkInterval: 16,
          rageFireInterval: 100 // 暴走时的发射间隔（毫秒）
        },
        enemy: {
          spawnInterval: 2000,
          fallSpeed: 5000,
          health: 5,
          rageSpawnInterval: 500 // 暴走时的生成间隔（毫秒）
        },
        rage: {
          duration: 5000,
          killCount: 3,
          bulletColumns: 5,
          enemySpeedup: 2
        },
        score: {
          basePoints: 10, // 基础得分
          popupDuration: 800 // 得分动画持续时间（毫秒）
        }
      }

      // 游戏控制变量
      let gameStarted = false
      let bulletInterval
      let enemyInterval
      let killCount = 0 // 击杀计数
      let isRageMode = false // 是否处于暴走模式
      let rageTimeout // 暴走模式计时器
      let score = 0
      let gameStartTime
      let gameTimer

      // 游戏统计数据
      let gameStats = {
        highScore: 0,
        totalKills: 0,
        longestTime: 0,
        shotsFired: 0,
        shotsHit: 0
      }

      // 开始游戏
      function startGame() {
        gameStarted = true
        startButton.style.display = 'none'
        player.classList.remove('game-paused')
        scoreContainer.style.display = 'block'
        score = 0
        scoreElement.textContent = '0'
        gameStartTime = Date.now()

        // 开始计时
        gameTimer = setInterval(updateGameTime, 1000)

        // 开始发射子弹
        bulletInterval = setInterval(() => {
          if (isRageMode) {
            // 暴走模式发射多列子弹
            const spread = 8 // 减小子弹展开范围（从20改为8）
            const step = spread / (gameConfig.rage.bulletColumns - 1)
            for (let i = 0; i < gameConfig.rage.bulletColumns; i++) {
              const offset = -spread / 2 + step * i
              createBullet(offset)
            }
          } else {
            // 普通模式发射单列子弹
            createBullet()
          }
        }, gameConfig.bullet.fireInterval)

        // 开始生成敌方飞船
        enemyInterval = setInterval(createEnemyShip, gameConfig.enemy.spawnInterval)
      }

      // 记录当前飞机的位置
      let playerPosition = gameConfig.player.initialPosition

      // 监听键盘事件
      document.addEventListener('keydown', (event) => {
        if (!gameStarted) return

        // 根据是否处于暴走模式计算移动速度
        const currentMoveSpeed = isRageMode ? gameConfig.player.moveSpeed * gameConfig.player.rageSpeedMultiplier : gameConfig.player.moveSpeed

        switch (event.key) {
          case 'ArrowLeft':
            playerPosition = Math.round(Math.max(playerPosition - currentMoveSpeed, 0))
            player.style.left = `${playerPosition}%`
            break
          case 'ArrowRight':
            playerPosition = Math.round(Math.min(playerPosition + currentMoveSpeed, 100))
            player.style.left = `${playerPosition}%`
            break
        }
      })

      // 检查碰撞
      function checkCollision(rect1, rect2) {
        return !(rect1.right < rect2.left || rect1.left > rect2.right || rect1.bottom < rect2.top || rect1.top > rect2.bottom)
      }

      // 创建敌方飞船
      function createEnemyShip() {
        const ship = document.createElement('img')
        ship.src = 'static/ship.svg'
        ship.className = 'enemy-ship'

        const position = Math.round(getRandomPosition())
        ship.style.left = `${position}%`
        ship.style.top = '0'
        ship.dataset.health = gameConfig.enemy.health

        gameContainer.appendChild(ship)

        const shipAnimation = ship.animate([{ top: '0' }, { top: '100%' }], {
          duration: gameConfig.enemy.fallSpeed,
          easing: 'linear'
        })

        shipAnimation.onfinish = () => {
          ship.remove()
        }

        // 添加与玩家的碰撞检测
        const checkPlayerCollision = setInterval(() => {
          if (!ship.isConnected || !gameStarted) {
            clearInterval(checkPlayerCollision)
            return
          }

          const shipRect = ship.getBoundingClientRect()
          const playerRect = player.getBoundingClientRect()

          if (checkCollision(shipRect, playerRect)) {
            gameOver()
            clearInterval(checkPlayerCollision)
          }
        }, gameConfig.bullet.checkInterval)
      }

      // 生成随机位置（百分比）
      function getRandomPosition() {
        return Math.random() * 100
      }

      // 创建子弹
      function createBullet(offsetX = 0) {
        gameStats.shotsFired++
        const bullet = document.createElement('div')
        bullet.className = `bullet ${isRageMode ? 'rage' : ''}`

        const exactPosition = playerPosition + offsetX
        bullet.style.left = `${exactPosition}%`
        bullet.style.bottom = '100px'

        gameContainer.appendChild(bullet)

        const bulletAnimation = bullet.animate([{ bottom: '100px' }, { bottom: '100%' }], {
          duration: gameConfig.bullet.speed,
          easing: 'linear'
        })

        const checkHit = setInterval(() => {
          if (!bullet.isConnected) {
            clearInterval(checkHit)
            return
          }

          const bulletRect = bullet.getBoundingClientRect()
          const ships = document.querySelectorAll('.enemy-ship')

          ships.forEach((ship) => {
            const shipRect = ship.getBoundingClientRect()

            if (checkCollision(bulletRect, shipRect)) {
              bullet.remove()
              clearInterval(checkHit)

              let health = parseInt(ship.dataset.health) - 1
              ship.dataset.health = health

              ship.classList.add('hit')
              setTimeout(() => ship.classList.remove('hit'), 200)

              if (health <= 0) {
                // 在飞船位置显示得分动画
                updateScore(gameConfig.score.basePoints, shipRect.left + shipRect.width / 2, shipRect.top + shipRect.height / 2)
                ship.remove()
                if (!isRageMode) {
                  killCount++
                  if (killCount >= gameConfig.rage.killCount) {
                    enterRageMode()
                  }
                }
              }

              if (checkCollision(bulletRect, shipRect)) {
                gameStats.shotsHit++
                // 更新命中率
                const accuracy = Math.round((gameStats.shotsHit / gameStats.shotsFired) * 100)
                accuracyElement.textContent = `${accuracy}%`
              }
            }
          })
        }, gameConfig.bullet.checkInterval)

        bulletAnimation.onfinish = () => {
          bullet.remove()
          clearInterval(checkHit)
        }
      }

      // 进入暴走模式
      function enterRageMode() {
        isRageMode = true
        document.getElementById('rage-indicator').style.display = 'block'

        // 清除现有定时器
        clearInterval(bulletInterval)
        clearInterval(enemyInterval)

        // 加快子弹发射
        bulletInterval = setInterval(() => {
          if (isRageMode) {
            const spread = 8
            const step = spread / (gameConfig.rage.bulletColumns - 1)
            for (let i = 0; i < gameConfig.rage.bulletColumns; i++) {
              const offset = -spread / 2 + step * i
              createBullet(offset)
            }
          } else {
            createBullet()
          }
        }, gameConfig.bullet.rageFireInterval) // 使用更快的发射间隔

        // 加快敌人生成
        enemyInterval = setInterval(createEnemyShip, gameConfig.enemy.rageSpawnInterval)

        // 5秒后退出暴走模式
        rageTimeout = setTimeout(exitRageMode, gameConfig.rage.duration)
      }

      // 退出暴走模式
      function exitRageMode() {
        isRageMode = false
        killCount = 0
        document.getElementById('rage-indicator').style.display = 'none'

        // 恢复正常速度
        clearInterval(bulletInterval)
        clearInterval(enemyInterval)

        // 恢复正常子弹发射间隔
        bulletInterval = setInterval(() => {
          createBullet()
        }, gameConfig.bullet.fireInterval)

        // 恢复正常敌人生成速度
        enemyInterval = setInterval(createEnemyShip, gameConfig.enemy.spawnInterval)
      }

      // 显示得分动画
      function showScorePopup(points, x, y) {
        const popup = document.createElement('div')
        popup.className = 'score-popup'
        popup.textContent = `+${points}`

        // 随机轻微偏移，让多个同时出现的分数不重叠
        const offsetX = (Math.random() - 0.5) * 30
        popup.style.left = `${x + offsetX}px`
        popup.style.top = `${y}px`

        gameContainer.appendChild(popup)

        // 添加3D效果
        popup.style.transform = `perspective(100px) translateZ(0)`

        // 动画结束后移除元素
        setTimeout(() => {
          popup.remove()
        }, gameConfig.score.popupDuration)
      }

      // 更新分数
      function updateScore(points, x, y) {
        const oldScore = score
        score += points

        // 数字递增动画
        const duration = 500
        const startTime = performance.now()

        function updateCounter(currentTime) {
          const elapsed = currentTime - startTime
          const progress = Math.min(elapsed / duration, 1)

          // 使用缓动函数使动画更平滑
          const easeProgress = 1 - Math.pow(1 - progress, 3)
          const currentScore = Math.floor(oldScore + points * easeProgress)

          scoreElement.textContent = currentScore

          if (progress < 1) {
            requestAnimationFrame(updateCounter)
          }
        }

        requestAnimationFrame(updateCounter)

        // 添加分数高亮动画
        scoreElement.classList.add('score-highlight')
        setTimeout(() => {
          scoreElement.classList.remove('score-highlight')
        }, 500)

        // 显示得分弹出动画
        showScorePopup(points, x, y)

        // 更新最高分
        if (score > gameStats.highScore) {
          gameStats.highScore = score
          highScoreElement.textContent = score
        }
      }

      // 格式化时间
      function formatTime(ms) {
        const seconds = Math.floor(ms / 1000)
        const minutes = Math.floor(seconds / 60)
        const remainingSeconds = seconds % 60
        return `${minutes}:${remainingSeconds.toString().padStart(2, '0')}`
      }

      // 更新游戏时间
      function updateGameTime() {
        const currentTime = Date.now()
        const duration = currentTime - gameStartTime
        gameDurationElement.textContent = formatTime(duration)
      }

      // 游戏结束
      function gameOver() {
        gameStarted = false
        clearInterval(bulletInterval)
        clearInterval(enemyInterval)
        clearInterval(gameTimer)
        clearTimeout(rageTimeout)

        // 移除所有子弹和敌人
        document.querySelectorAll('.bullet, .enemy-ship').forEach((el) => el.remove())

        // 显示游戏结束界面
        gameOverContainer.style.display = 'block'
        finalScoreElement.textContent = score
        player.classList.add('game-paused')
        document.getElementById('rage-indicator').style.display = 'none'

        // 更新统计数据
        const gameDuration = Date.now() - gameStartTime
        if (gameDuration > gameStats.longestTime) {
          gameStats.longestTime = gameDuration
          longestTimeElement.textContent = formatTime(gameDuration)
        }

        // 添加历史记录
        const historyItem = document.createElement('div')
        historyItem.className = 'history-item'
        historyItem.innerHTML = `
          <div>得分: ${score}</div>
          <div class="history-time">时长: ${formatTime(gameDuration)}</div>
        `
        historyList.insertBefore(historyItem, historyList.firstChild)

        // 限制历史记录数量
        if (historyList.children.length > 5) {
          historyList.removeChild(historyList.lastChild)
        }
      }

      // 重新开始游戏
      function restartGame() {
        gameOverContainer.style.display = 'none'
        score = 0
        killCount = 0
        isRageMode = false
        playerPosition = gameConfig.player.initialPosition
        player.style.left = `${playerPosition}%`
        startGame()
      }

      // 定期更新击杀速率
      setInterval(() => {
        if (gameStarted) {
          const minutesPlayed = (Date.now() - gameStartTime) / 60000
          const killRate = Math.round((killCount / minutesPlayed) * 10) / 10
          killRateElement.textContent = `${killRate}/分钟`
        }
      }, 1000)

      // 监听开始按钮点击
      startButton.addEventListener('click', startGame)
      // 监听重新开始按钮点击
      restartButton.addEventListener('click', restartGame)
    </script>
  </body>
</html>
